package cn.rdq.iknessplatform.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.rdq.common.CommonResult;
import cn.rdq.common.exception.ExceptionStatus;
import cn.rdq.common.util.RedisUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisUtil redisUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("IKness-Token");
        if (StringUtils.isEmpty(token)) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
//            response.getWriter().print(failed);
            CommonResult failed = CommonResult.success().failed(ExceptionStatus.TokenExpired);
            response.getWriter().append(failed.toString());
            return false;
        }
        if (ObjectUtil.isEmpty(redisUtil.get(token))) {
//            response.getWriter().print(failed);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json;charset=utf-8");
            CommonResult failed = CommonResult.success().failed(ExceptionStatus.TokenExpired);
            response.getWriter().append(failed.toString());
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
